package com.cf.mvp.base;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleRegistry;

import com.cf.mvp.mvp.IBaseView;
import com.cf.mvp.mvp.IPresenter;
import com.cf.mvp.mvp.proxy.ProxyImpl;
import com.cf.mvp.rx.LifecycleToRxSubject;

import io.reactivex.subjects.BehaviorSubject;

/**
 * @author yangji
 */
public class BaseView<P extends IPresenter> implements IBaseView {

    private LifecycleToRxSubject subject = LifecycleToRxSubject.create();

    private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

    @Override
    public BehaviorSubject<Lifecycle.Event> getSubject() {
        return subject.getSubject();
    }

    private ProxyImpl<P> proxyPresenter;

    public P getPresenter() {
        return proxyPresenter.getMainPresenter();
    }

    //模拟方法
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        proxyPresenter = new ProxyImpl<P>() {
        };
        proxyPresenter.bindPresenter(this);
        getLifecycle().addObserver(subject);
    }

    protected void onDestroy() {
        if (proxyPresenter != null) {
            proxyPresenter.unBindPresenter();
        }
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
}
